package com.hellojava.service;

import com.hellojava.assembler.OcrHistoryAssembler;
import com.hellojava.cache.OcrHistoryCache;
import com.hellojava.dto.OcrHistoryDto;
import com.hellojava.entity.OcrHistory;
import com.hellojava.jpa.OcrHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author dengjihai
 * @create 2017-12-22
 **/
@Service
public class OcrHistoryService {

    @Autowired
    OcrHistoryRepository ocrHistoryRepository;

    @Autowired
    OcrHistoryCache ocrHistoryCache;

    /**
     * 保存识别结果
     * @param ocrHistoryDto
     * @return
     */
    public String save(OcrHistoryDto ocrHistoryDto){
        OcrHistory ocrHistory = OcrHistoryAssembler.convertDtoToEntity(ocrHistoryDto);
        return ocrHistoryRepository.save(ocrHistory).getId();
    }

    /**
     * 通过用户id查询出所有的识别结果
     * @return
     */
    public List<OcrHistoryDto> getOcrHistoryByOpenId(String openId){
        return  OcrHistoryAssembler.convertToListDto(ocrHistoryRepository.findByOpenIdOrderByCreateTimeDesc(openId));
    }


    /**
     * 通过logid 查询详细
     * @param logId
     * @return
     */
    public OcrHistoryDto getOcrHistoryByLogId(String logId){

        OcrHistoryDto ocrHistoryDto =ocrHistoryCache.getOcrHistory(logId);
        if(ocrHistoryDto!=null){
            return ocrHistoryDto;
        }

        OcrHistory ocrHistory=ocrHistoryRepository.findByLogId(logId);
        ocrHistoryDto =OcrHistoryAssembler.convertToDto(ocrHistory);
        ocrHistoryCache.saveOcrHistory(logId,ocrHistoryDto);
        return ocrHistoryDto;
    }

}
